import { Button, Popconfirm, Tooltip, Input, Tag, Icon } from "antd";
import React from "react";
import { deleteOneType, insertOneType, loadType } from "@service/form";

export default class ClassifyButton extends React.Component {
  static getDerivedStateFromProps(nextProps) {
    // Should be a controlled component.
    if ("value" in nextProps) {
      return {
        ...(nextProps.value || {}),
      };
    }
    return null;
  }

  constructor(props) {
    super(props);
    const value = props.value || {};
    this.state = {
      value,
      inputVisible: false,
      inputValue: "",
      tags: [],
      currentIndex: -1,
    };
  }

  componentDidMount() {
    this.getTypes();
  }

  getTypes = async () => {
    const result = await loadType();
    const index = result.data.findIndex(i => i.name === this.state.value);
    this.setState({
      currentIndex: index,
      tags: result.data,
    });
  };

  handleChange = (value, index) => {
    if (!("value" in this.props)) {
      this.setState({
        value,
      });
    }
    this.setState({
      currentIndex: index,
    });
    // this.state.tags[index].nowShow = !this.state.tags[index].nowShow;
    this.triggerChange(value);
  };

  triggerChange = changedValue => {
    // Should provide an event to pass value to Form.
    const { onChange } = this.props;
    if (onChange) {
      onChange(changedValue);
    }
  };

  handleInputDelete = async id => {
    const list = await deleteOneType(id);
    if (list) {
      this.getTypes();
    }
  };

  showInput = () => {
    this.setState({ inputVisible: true }, () => this.input.focus());
  };

  handleInputChange = e => {
    this.setState({ inputValue: e.target.value });
  };

  handleInputConfirm = async () => {
    const { inputValue } = this.state;
    if (inputValue) {
      const list = await insertOneType(inputValue);
      if (list) {
        this.getTypes();
      }
    }
    this.setState({
      inputVisible: false,
      inputValue: "",
    });
  };

  saveInputRef = input => {
    this.input = input;
  };

  render() {
    const { value, inputVisible, inputValue, tags, currentIndex } = this.state;
    return (
      <div>
        {tags.map((tag, index) => {
          const isLongTag = tag.name.length > 30;
          const tagElem = (
            <div style={{ display: "inline-block" }} key={index}>
              <Button
                // className="button"
                key={index}
                name={tag.name}
                value={value}
                onClick={() => this.handleChange(tag.name, index)}
                style={{ paddingLeft: 14, paddingRight: 14, marginRight: 15 }}
                className={currentIndex === index ? 'active' : 'nowActive'}
              >
                {isLongTag ? `${tag.name.slice(0, 30)}...` : tag.name}
              </Button>
              <Popconfirm
                placement="top"
                title="是否删除？"
                okText="确定"
                cancelText="取消"
                onConfirm={() => this.handleInputDelete(tag._id)}
              >
                <a
                  className={currentIndex === index ? 'nowShow' : 'show'}
                  title="删除"
                >
                  -
                </a>
              </Popconfirm>
            </div>
          );
          return isLongTag ? (
            <Tooltip title={tag.name} key={tag.name}>
              {tagElem}
            </Tooltip>
          ) : (
            tagElem
          );
        })}
        {inputVisible && (
          <Input
            ref={this.saveInputRef}
            type="text"
            style={{ width: 80 }}
            value={inputValue}
            onChange={this.handleInputChange}
            onBlur={this.handleInputConfirm}
            onPressEnter={this.handleInputConfirm}
          />
        )}
        {!inputVisible && (
          <Tag
            onClick={this.showInput}
            style={{
              background: "#fff",
              borderStyle: "dashed",
              paddingTop: 4,
              paddingBottom: 4,
              paddingLeft: 8,
              paddingRight: 8,
            }}
          >
            <Icon type="plus" />
          </Tag>
        )}
      </div>
    );
  }
}
